package com.shuoyue.ycgk.ui.questionbank.practice.estamate;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.entity.Option;
import com.shuoyue.ycgk.entity.QuestionParent;
import com.shuoyue.ycgk.entity.QuestionSimple;
import com.shuoyue.ycgk.ui.questionbank.BaseCountActivity;
import com.shuoyue.ycgk.ui.questionbank.CountInfoBean;
import com.shuoyue.ycgk.ui.questionbank.practice.QuestionSpecialCountAdapter;
import com.shuoyue.ycgk.ui.questionbank.practice.checkall.CheckQuestionAllActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.checkwrongs.CheckQuestionWrongActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.specialtraining.EpInfo;
import com.shuoyue.ycgk.utils.GridSpacingItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.TimeFomatUtil;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 模考答题结果统计
 */
public class EstamateCountActivity extends BaseCountActivity {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_num)
    TextView rightNum;
    @BindView(R.id.total_num)
    TextView totalNum;
    @BindView(R.id.right_rate)
    TextView rightRate;
    @BindView(R.id.use_time)
    TextView useTime;
    @BindView(R.id.answerCard)
    RecyclerView answerCard;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.score)
    TextView score;
    @BindView(R.id.totalScore)
    TextView totalScore;

    List<QuestionParent> questionParents;

    QuestionSpecialCountAdapter questionSpecialCountAdapter;
    String pagerName = "";


    public static void start(Context source,
                             String name,
                             ArrayList<QuestionParent> questionParents) {
        source.startActivity(new Intent(source, EstamateCountActivity.class)
                .putExtra("epName", name)
                .putExtra("questions", questionParents)
        );
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_question_set_count;
    }

    @Override
    protected void initView() {
        answerCard.setLayoutManager(new GridLayoutManager(mContext, 5));
        answerCard.addItemDecoration(new GridSpacingItemDecoration(5, SizeUtil.dip2px(mContext, 20), false));

    }

    @Override
    public void initData() {
        questionParents = (List<QuestionParent>) getIntent().getSerializableExtra("questions");
        pagerName = getIntent().getStringExtra("epName");
        setCommonUI();
        setTypeUI();
        scrollView.scrollTo(0, 0);
    }

    void setTypeUI() {
        List<QuestionSimple> allSimple = allSimple(questionParents);
        HashMap<EpInfo, List<QuestionSimple>> epidType = new HashMap<>();
        for (QuestionSimple questionSimple : allSimple) {
            if (questionSimple.getExaminationPointDTOS() != null) {
                for (EpInfo epInfo : questionSimple.getExaminationPointDTOS()) {
                    List<QuestionSimple> mapVlue = epidType.get(epInfo);
                    if (mapVlue == null) {
                        mapVlue = new ArrayList<>();
                        epidType.put(epInfo, mapVlue);
                    }
                    mapVlue.add(questionSimple);
                }
            }
        }

        List<CountInfoBean> countInfos = new ArrayList<>();
        for (Map.Entry<EpInfo, List<QuestionSimple>> entry : epidType.entrySet()) {
            List<QuestionSimple> questionParents = entry.getValue();
            CountInfoBean countInfo = new CountInfoBean();
            countInfo.setTypeStr(entry.getKey().getEpName());
            for (QuestionSimple questionSimple : questionParents) {
                handleQuestionSimple(questionSimple, countInfo);
            }
            countInfos.add(countInfo);
        }
    }

    void setCommonUI() {
        title.setVisibility(TextUtils.isEmpty(pagerName) ? View.GONE : View.VISIBLE);
        title.setText(pagerName);
        CountInfoBean countInfo = count(questionParents);
        rightNum.setText(countInfo.getRightQuestion() + "");
        totalNum.setText(countInfo.getTotalQuestion() + "");
        rightRate.setText("正确率:"
                + (int) (((Float.valueOf(countInfo.getRightQuestion()) / Float.valueOf(countInfo.getTotalQuestion()))) * 100)
                + "%");
//        useTime.setText("用时" + TimeFomatUtil.formatmmss((long) (countInfo.getTimeMul() / 1000)));

        useTime.setText("用时" + TimeFomatUtil.formatmmss((long) (countInfo.getTimeMul() / 1000)));

        List<QuestionSimple> allSimple = allSimple(questionParents);
        questionSpecialCountAdapter = new QuestionSpecialCountAdapter(allSimple);
        answerCard.setAdapter(questionSpecialCountAdapter);
        questionSpecialCountAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            QuestionSimple questionSimple = (QuestionSimple) adapter.getItem(position);
            CheckQuestionAllActivity.start(mContext, pagerName, (ArrayList<QuestionParent>) questionParents, questionSimple);
        });
        totalScore.setText(countInfo.getTotalScore() % 1f == 0 ?
                String.valueOf((int) countInfo.getTotalScore()) :
                String.valueOf(countInfo.getTotalScore())
        );
        score.setText(countInfo.getMyScore() % 1f == 0 ?
                String.valueOf((int) countInfo.getMyScore()) :
                String.valueOf(countInfo.getMyScore())
        );
//        score.setText(String.valueOf(countInfo.getMyScore()));
    }

    /**
     * 提取基础题目
     */
    private List<QuestionSimple> allSimple(List<QuestionParent> questionParents) {
        List<QuestionSimple> allSimple = new ArrayList<>();
        for (QuestionParent questionParent : questionParents) {
            //
            if (questionParent.getIsMaterial() == 1) {
                //材料题
                for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                    allSimple.add(questionSimple);
                }
            } else {
                allSimple.add(questionParent.getQuestionSimpleDTOS().get(0));
            }
        }
        return allSimple;
    }

    /**
     * 统计
     * 1:正确个数
     * 2:总提数
     * 3.计算正确率
     * 4计算用时
     * 5:是否有错题
     * 6.分类正确率
     */
    CountInfoBean count(List<QuestionParent> questionParents) {
        //
        CountInfoBean countInfo = new CountInfoBean();
        for (QuestionParent questionParent : questionParents) {
            //
            if (questionParent.getIsMaterial() == 1) {
                //材料题
                for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                    handleQuestionSimple(questionSimple, countInfo);
                }
            } else {
                handleQuestionSimple(questionParent.getQuestionSimpleDTOS().get(0), countInfo);
            }
        }
        return countInfo;
    }

    void handleQuestionSimple(QuestionSimple questionSimple, CountInfoBean countInfo) {
        //标记为查看答案
        questionSimple.setShowRight(true);
        countInfo.setTotalScore(countInfo.getTotalScore() + questionSimple.getScore());

        //1.标记是否答对
        if (questionSimple.getMyChooseAnswer() != null &&
                questionSimple.getMyChooseAnswer().size() > 0) {
            //有作答
            StringBuilder sbMine = new StringBuilder();
            for (String o : questionSimple.getMyChooseAnswer()) {
                sbMine.append(o);
            }
            StringBuilder sbRight = new StringBuilder();
            for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
                if (o.isRight()) sbRight.append(o.getNo());
            }
            //答对提数+1
            countInfo.setRightQuestion(countInfo.getRightQuestion()
                    + (sbRight.toString().equals(sbMine.toString()) ? 1 : 0));
            countInfo.setMyScore(countInfo.getMyScore()
                    + (sbRight.toString().equals(sbMine.toString()) ? questionSimple.getScore() : 0));
            //标记是否正确
            questionSimple.setIsAnswerRight(sbRight.toString().equals(sbMine.toString()) ? 1 : 0);
            //增加答题时间(毫秒)
            countInfo.setTimeMul(countInfo.getTimeMul() + questionSimple.getUseTime());
        } else {
            questionSimple.setIsAnswerRight(2);
        }

        //2.总提数加1
        countInfo.setTotalQuestion(countInfo.getTotalQuestion() + 1);
        //
    }

    @OnClick({R.id.back, R.id.wrongs, R.id.rights})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.wrongs:
                CheckQuestionWrongActivity.start(mContext, pagerName, getQuestiongWrongs(questionParents));
                break;
            case R.id.rights:
                CheckQuestionAllActivity.start(mContext, pagerName, (ArrayList<QuestionParent>) questionParents);
                break;
        }
    }

//    @Override
//    public void finish() {
//        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "退出", "是否确认退出");
//        hintConfirmDialog.setOkListener(v -> {
//            super.finish();
//            hintConfirmDialog.dismiss();
//        });
//        hintConfirmDialog.show();
//    }

//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        // TODO: add setContentView(...) invocation
//        ButterKnife.bind(this);
//    }
}
